﻿using System;
using System.Collections.Generic;

namespace DeploySources.MVVM
{
	/// <summary>
	/// Communicate between ViewModels
	/// </summary>
	public static class Mediator
	{
		static readonly IDictionary<string, List<Action<object>>> PlDict = new Dictionary<string, List<Action<object>>>();

		/// <summary>
		/// Register a listener to command tokens
		/// </summary>
		/// <param name="token">Represents the command for communication</param>
		/// <param name="callback">Method to call</param>
		public static void Register(string token, Action<object> callback)
		{
			if (!PlDict.ContainsKey(token))
			{
				var list = new List<Action<object>> {callback};
				PlDict.Add(token, list);
			}
			else
			{
				bool found = false;
				foreach (var item in PlDict[token])
					if (item.Method.ToString() == callback.Method.ToString())
						found = true;
				if (!found)
					PlDict[token].Add(callback);
			}
		}

		/// <summary>
		/// RUnrgister a listener to command tokens
		/// </summary>
		/// <param name="token">Represents the command for communication</param>
		/// <param name="callback">Method to call</param>
		public static void Unregister(string token, Action<object> callback)
		{
			if (PlDict.ContainsKey(token))
				PlDict[token].Remove(callback);
		}

		/// <summary>
		/// push a notification to all listeners
		/// </summary>
		/// <param name="token">Represents the command for communication</param>
		/// <param name="args">Arguments for the listeners</param>
		public static void NotifyColleagues(string token, object args)
		{
			if (PlDict.ContainsKey(token))
				foreach (var callback in PlDict[token])
					callback(args);
		}

	}
}
